import React from 'react'
import { Form, Input, Button, message } from 'antd';
import { login, reset } from '../../api/index'
import { withRouter } from 'react-router-dom'
import './login.css'

function Login(props) {
    let userRef = null
    // 登录
    const onFinish = values => {
        login(values).then(res => {
            if (res.data.code === '1') {
                localStorage.setItem('token', res.data.token)
                props.history.push('/home/housing')
                message.success(res.data.msg);
            } else {
                message.error(res.data.msg);
            }
        })
    }
    // 注册
    const onReset = () => {
        userRef.validateFields().then(useDate => {
            reset(useDate).then(res => {
                if (res.data.code === '1') {
                    message.error(res.data.msg);
                } else {
                    message.success(res.data.msg);
                }
            })
        })
    }

    return (
        <div className="login-main">
            <div className="login">
            <Form name="basic" onFinish={onFinish} ref={(ref) => { userRef = ref }}>
                <Form.Item
                    label="账号"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名' }]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="密码"
                    name="password"
                    rules={[{ required: true, message: '请输入密码' }]}
                >
                    <Input.Password />
                </Form.Item>

                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                    <Button type="primary" htmlType="submit" className="btn">登录</Button>
                    <Button type="primary" onClick={(e) => onReset()} className="reset">注册</Button>
                </Form.Item>
            </Form>
        </div>
        </div>
        
    )

}

export default withRouter(Login)
